//
//  PSMove.m
//  PrefCore
//
//  Created by Sergey on 5/13/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSMove.h"
#import "PSNode.h"

@interface PSMove () {
    PSCardIndex _cards[PS_GAME_PLAYERS];
}

-(void)setCard0:(PSCard*)c0
          card1:(PSCard*)c1
          card2:(PSCard*)c2
        andNode:(PSNode*)node;

@end

@implementation PSMove

+(PSObjectPool*)pool {
    static PSObjectPool *pool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pool = [[PSObjectPool alloc] initWithCreateObject:^{
            return [[PSMove alloc] init];
        }];
    });
    return pool;
}

-(PSCardIndex) c0 {
    return _cards[0];
}

-(PSCardIndex) c1 {
    return _cards[1];
}

-(PSCardIndex) c2 {
    return _cards[2];
}

-(void)setCard0:(PSCard*)c0
          card1:(PSCard*)c1
          card2:(PSCard*)c2
        andNode:(PSNode*)node {
    _cards[0] = c0.compressed;
    _cards[1] = c1.compressed;
    _cards[2] = c2.compressed;
    _node = node;
    _node.parents++;
}

+(instancetype)moveWithCard0:(PSCard*)c0
                       card1:(PSCard*)c1
                       card2:(PSCard*)c2
                     andNode:(PSNode*)node {
    PSMove *res = [[PSMove pool] get];
    [res setCard0:c0 card1:c1 card2:c2 andNode:node];
    return res;
}

-(PSCardIndex)cardForPlayerId:(PSPlayerId)playerId {
    NSAssert(playerId < PS_GAME_PLAYERS, @"Invalid player ID.");
    return _cards[playerId];
}

-(void)destroyWithRecycle:(BOOL)recycle {
    NSAssert(_node.parents != 0, @"Node parents cannot become negative.");
    _node.parents--;
    _node = nil;
    if (recycle) {
        [[PSMove pool] putObject:self];
    }
}

-(NSString*)description {
    return [NSString stringWithFormat:@"%@ %@ %@"
    ,   [PSCard cardWithIndex:_cards[0]]
    ,   [PSCard cardWithIndex:_cards[1]]
    ,   [PSCard cardWithIndex:_cards[2]]
    ];
}

@end
